<template>
  <div class="home-div">
    <van-nav-bar :title="getTitle()" @click-left="onClickLeft" @click-right="onClickRight" fixed>
      <template #left v-if="isShowLeft()">
        <van-icon name="arrow-left" size="25" />
      </template>
      <template #right v-if="isShowRight() && permission.create">
        <van-icon name="plus" size="25" />
      </template>
    </van-nav-bar>
    <div :style="{ marginTop: '75px' }" @touchstart="getTouchStart()" @touchend="getTouchEnd()">
      <div class="state-bar" v-if="!wsState">订阅推送服务未连接！</div>
      <router-view />
    </div>
    <van-popup v-model="show" position="bottom" :style="{ height: '45%' }">
      <van-picker title="选择任务类型" show-toolbar :columns="taskTypes" @confirm="onConfirm" @cancel="onCancel"
        :default-index="0" />
    </van-popup>
  </div>
</template>

<script>
import { mapGetters, mapMutations, createNamespacedHelpers } from 'vuex'
import { initData } from './TaskList.vue'
import { eventBus } from '../bus'
import { getStationNames } from '@/api/line_data'
import { getMyPermission, getUserInfo, getTaskSetting } from '../utils/taskUtils'
const taskCreateStore = createNamespacedHelpers('taskCreate')
export default {
  name: 'HOME',
  components: {},
  props: {},
  data() {
    return {
      wsState: false,
      touchLoop: 0,
      version: 'V1.000.050.00',
      taskTypes: ['工务作业', '电务作业', '列检作业', '商检作业', '巡道作业', '其它作业'],
      show: false,
      taskCreatePath_Normal: '/taskcreate/Normal',
      taskCreatePath_GW: '/taskcreate/GW',
      taskCreatePath_DW: '/taskcreate/DW',
      taskCreatePath_XD: '/taskcreate/XD',
      taskCreatePath_LJ: '/taskcreate/LJ',
      taskCreatePath_SJ: '/taskcreate/SJ',
      taskCreatePath_QT: '/taskcreate/QT',
      taskCreatePath_DC: '/taskcreate/DC',
      taskCreatePath_JW: '/taskcreate/JW',
      taskInfoPath: '/taskInfo'
    }
  },
  computed: {
    ...mapGetters(['userId', 'deviceId', 'permission', 'workType', 'station', 'taskSetting'])
  },
  watch: {},
  created() {
    window.getDataFromNative = this.getDataFromNative
   },
  mounted() {
    this.$socket.open()
  },
  beforeDestroy() {
    this.$socket.close()
  },
  destroyed() {
    delete window.getDataFromNative
  },
  sockets: {
    connect() {
      console.log('[Home] ws connected')
      this.wsState = true
      this.$toast('与订阅推送服务连接成功！')
      this.$socket.emit('Subscribe', { channels: ['TaskChangeBriefInfo'] }, (ackData) => {
        ackData.ack_channels.forEach((chn) => {
          console.log(`[Home] subscribe channel-${chn} success`)
        })
      })
    },
    disconnect() {
      this.$toast('与订阅推送服务连接中断！')
      this.wsState = false
      console.log('[Home] ws disconnected')
    },
    reconnect() {
      this.wsState = true
      this.$toast('与订阅推送服务连接恢复！')
      console.log('[Home] ws reconnected')
    }
  },
  methods: {
    ...mapMutations(['setUserId', 'setDeviceId', 'setPermission', 'setOrgIds', 'setMyStationIds', 'setStationIds', 'setWorkType', 'setStation', 'setTaskSetting']),
    ...taskCreateStore.mapMutations(['initTaskCreateStore']),
    async getDataFromNative(deviceId, userId) {
      this.$toast('页面初始化加载中')
      const response = await getTaskSetting()
      if (response.code === 0) this.setTaskSetting(response.data.taskSetting)
      if (!this.taskSetting) {
        this.$toast('页面初始化加载失败')
      }
      this.setUserId(0)
      this.setDeviceId(0)
      this.setPermission({})
      this.setOrgIds(0)
      this.setWorkType([])
      this.setStation(0)
      this.setMyStationIds([])
      this.setStationIds([])
      if (deviceId) {
        this.setDeviceId(parseInt(deviceId))
      } else {
        this.setDeviceId(0)
      }
      if (userId) {
        this.setUserId(parseInt(userId))
        if (this.taskSetting.defaultPremissions) {
          this.setPermission(this.taskSetting.defaultPremissions)
        } else {
          getMyPermission(parseInt(this.userId), 0).then((response) => {
            if (response.code === 0) {
              this.setPermission(response.data.op_perm.task)
            }
          })
        }
        getUserInfo(parseInt(userId)).then((response) => {
          if (response.code === 0) {
            this.setStation(response.data.stationIds)
            this.setOrgIds(response.data.org)
            if (this.taskSetting.defaultStationIds) {
              this.setStation(this.taskSetting.defaultStationIds)
            }
            if (this.taskSetting.defaultOrg) {
              this.setOrgIds(this.taskSetting.defaultOrg)
            }
            if (response.data.job) {
              switch (response.data.job) {
                case '电务': this.setWorkType([2])
                  break
                case '工务': this.setWorkType([1])
                  break
                case '列检': this.setWorkType([4])
                  break
                case '商检': this.setWorkType([8])
                  break
                case '调车': this.setWorkType([7])
                  break
                case '机务': this.setWorkType([6])
                  break
                default: this.setWorkType([0])
              }
            } else this.setWorkType([0])
            if (response.data.taskTypeIds) {
              this.setWorkType(response.data.taskTypeIds)
            }
            initData()
            getStationNames().then((res) => {
              var stationNameData = res.data
              var stationNameList = []
              var stationNameList2 = []
              for (var key in stationNameData) {
                stationNameList2.push({
                  text: stationNameData[key].stationName,
                  value: stationNameData[key].stationNum
                })
                if (this.station.includes(stationNameData[key].stationNum)) {
                  stationNameList.push({
                    text: stationNameData[key].stationName,
                    value: stationNameData[key].stationNum
                  })
                }
              }
              this.setStationIds(stationNameList2)
              this.setMyStationIds(stationNameList)
            })
          }
        })
      } else {
        this.setUserId(0)
      }
      this.$toast(`did:${deviceId},uid:${userId}`)
      eventBus.$emit('IdChange', { deviceId, userId })
    },
    getURLParams(url) {
      const param = url.split('#')[0] // 获取#/之前的字符串
      var paramContent = param.split('?')[1] // 获取?之后的参数字符串
      var paramsArray = paramContent.split('&') // 参数字符串分割为数组
      var paramResult = {}
      // 遍历数组，拿到json对象
      paramsArray.forEach((item, index, paramsArray) => {
        paramResult[paramsArray[index].split('=')[0]] = paramsArray[index].split('=')[1]
      })
      return paramResult
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    onClickRight() {
      if (!this.userId) {
        this.$dialog.alert({
          message: '创建任务，请先登录！'
        })
      } else {
        if (!this.deviceId) {
          this.$dialog.alert({
            message: '无当前防护设备信息，无法创建！'
          })
        } else {
          this.show = true
        }
      }
    },
    isShowLeft() {
      return this.$router.currentRoute.path !== '/'
    },
    isShowRight() {
      return this.$router.currentRoute.path.indexOf('taskcreate') < 0
    },
    getTouchStart() {
      clearTimeout(this.touchLoop) // 再次清空定时器，防止重复注册定时器
      this.touchLoop = setTimeout(this.HandleLongTouch, 2000)
    },
    getTouchEnd() {
      clearTimeout(this.touchLoop) // 清空定时器，防止重复注册定时器
    },
    HandleLongTouch() {
      this.$toast(`任务WEB版本\n${this.version}`)
    },
    getTitle() {
      let titleName = '任务列表'
      const path = this.$router.currentRoute.path
      if (path.indexOf('/taskcreate/Normal') >= 0) {
        titleName = '新建普通任务'
      } else if (path.indexOf('/taskcreate/GW') >= 0) {
        titleName = '新建工务作业'
      } else if (path.indexOf('/taskcreate/DW') >= 0) {
        titleName = '新建电务作业'
      } else if (path.indexOf('/taskcreate/XD') >= 0) {
        titleName = '新建巡道任务'
      } else if (path.indexOf('/taskcreate/LJ') >= 0) {
        titleName = '新建列检任务'
      } else if (path.indexOf('/taskcreate/SJ') >= 0) {
        titleName = '新建商检任务'
      } else if (path.indexOf('taskInfo') >= 0) {
        titleName = '任务详情'
      } else {
      }
      return titleName
    },
    onConfirm(val, index) {
      this.show = false
      this.initTaskCreateStore()
      // switch (index) {
      //   case 0:
      //     this.$router.push({ path: this.taskCreatePath_normal })
      //     break
      //   case 1:
      //     this.$router.push({ path: this.taskCreatePath_GW })
      //     break
      //   case 2:
      //     this.$router.push({ path: this.taskCreatePath_DW })
      //     break
      //   case 3:
      //     this.$router.push({ path: this.taskCreatePath_XD })
      //     break
      //   case 4:
      //     this.$router.push({ path: this.taskCreatePath_LJ })
      //     break
      //   default:
      //     break
      // }
      switch (index) {
        case 0:
          this.$router.push({ path: this.taskCreatePath_GW })
          break
        case 1:
          this.$router.push({ path: this.taskCreatePath_DW })
          break
        case 2:
          this.$router.push({ path: this.taskCreatePath_LJ })
          break
        case 3:
          this.$router.push({ path: this.taskCreatePath_SJ })
          break
        case 4:
          this.$router.push({ path: this.taskCreatePath_XD })
          break
        case 5:
          this.$router.push({ path: this.taskCreatePath_QT })
          break
        case 6:
          this.$router.push({ path: this.taskCreatePath_JW })
          break
        default:
          break
      }
    },
    onCancel() {
      this.show = false
    }
  }
}
</script>

<style lang="less" scoped>
// /deep/ .van-nav-bar__content {
//   height: 120px;
// }
// /deep/ .van-nav-bar__title {
//   font-size: 40px;
// }
.state-bar {
  height: 60px;
  background-color: red;
  color: white;
  text-align: center;
  font-size: 28px;
  line-height: 60px;
}
</style>
